# -*- coding: utf-8 -*-
from filesonline.models import User, File, Profile, ATTRIBUTE_TYPES,\
    TextAttribute, IntegerAttribute, DecimalAttribute, DateAttribute
from django.http import HttpResponse
from django.utils import simplejson
from django.utils.translation import ugettext as _
import logging
import os
import json
import settings
import mimetypes

from django.core.servers.basehttp import FileWrapper
log=logging.getLogger(__name__)

def json_error(o):
    respo = HttpResponse(simplejson.dumps(o), mimetype="application/javascript")
    return respo

def json_ok(o=''):
    respo = HttpResponse(simplejson.dumps(o), mimetype="application/javascript")
    print respo
    return respo

def login(request):
    log.debug(request.REQUEST)
    try:
        user = User.objects.get(login=request.REQUEST['login'])
        if user.check_password(request.REQUEST['password']):
            request.session['user'] = user
            request.session.save()
            return json_ok({'session_key': request.session.session_key, 'user': str(user)})
        else:
            return json_error({'wrongPassword':"Wrong password"})
    except:
        log.exception('invalid user')
        return json_error(_("Invalid user"))

def logout(request):
    user = request.session.get('user', None)
    if user:
        del request.session['user']
    return json_ok()

def get_profiles(request):
    try:
        user = request.session.get('user', None)
        profiles = []
        for profile in user.profile_set.all():
            profiles.append(profile.to_json())
        zwrot = json_ok(profiles)

    except Exception, e:
        log.exception('invalid user',e)
    return zwrot

def list_profile(request):
    idx = request.GET.get('profile_id', None)
    profile = Profile.objects.get(id=idx)
    files = []
    try:
        for f in profile.file_set.all().filter(active='True'):
            files.append(f.to_json())
    except Exception, e:
        log.exception('list_profiles ex %s'%e)
    
    zwrot = json_ok(files)
    return zwrot

def upload(request):
    log.debug("REQUEST %s" % str(request.REQUEST))
    user = request.session.get('user', None)
    try:
        profile = Profile.objects.get(id=request.REQUEST['profile_id'])
        body = request.FILES['file']
        
        parent = File.objects.filter(name=body.name).filter(user=user).filter(active=True)
        # u parenta active na null
        
        f = File()
        f.user = user
        f.size = body.size
        f.name = body.name
        f.profile = profile
        if parent:
            f.parent = parent[0]
            parent[0].active = False
            
            parent[0].save()
            
        f.save()
        for pa in profile.profile_attributes():
            if pa.type == ATTRIBUTE_TYPES.TEXT:
                attr = TextAttribute()
            elif pa.type == ATTRIBUTE_TYPES.INTEGER:
                attr = IntegerAttribute()
            elif pa.type == ATTRIBUTE_TYPES.DECIMAL:
                attr = DecimalAttribute()
            elif pa.type == ATTRIBUTE_TYPES.DATE:
                attr = DateAttribute()
            # TODO: Dopisać obsługę choice attribute
            else:
                return json_error(_("Invalid attribute type %s") % pa.name)
            # pobieranie wartosci atrybutu
            if request.REQUEST.has_key('attr_%d'%pa.id):
                attr.value = request.REQUEST['attr_%d'%pa.id]
            else:
                attr.value = pa.default_value if pa.mandatory else None
            attr.file = f
            attr.profile_attribute = pa
            #attr.save()
            
        # zapis ciała pliku
        d = settings.STORAGE + request.POST.get("profileName")
        if not os.path.exists(d):
            os.makedirs(d)
        destination = open( d + body.name, 'wb+')
        for chunk in body.chunks():
            destination.write(chunk)
        destination.close()
                
        return json_ok()
    except Exception, e:
        log.exception('Upload error')
        return json_error(_('Upload error'))
    
def download(request):
    idx = request.GET.get('file_id', None)
    try:
        f = File.objects.get(id=idx)
    except File.DoesNotExist:
        return json_error(_("File doesn't exist"))
    

def download_body(request):
    """
        Pobiera ciało pliku
    """
    idx = request.GET.get('file_id', None)
    user = request.session.get('user', None)
    
    try:
        f = File.objects.get(id=idx)
    except File.DoesNotExist:
        return json_error(_("File doesn't exist"))
    
    wrapper = FileWrapper(open(f.path, 'rb'))
    format, enc = mimetypes.guess_type(f.path, strict=True)
    response = HttpResponse(wrapper, content_type=format)
    response['Content-Length'] = os.path.getsize(f.path)
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(f.path)

    return response


def versioning(request):
    idx = request.GET.get('file_id', None)
    try: 
        f = File.objects.get(id=idx)
    except File.DoesNotExist:
        return json_error(_("File doesn't exist"))
    
    try:
        while f.parent:
            f=f.parent
        L = [f]
        toReturn = []
        
        for i in L:
            L.extend(list(i.file_set.all()))
        
        for t in L:
            toReturn.append(t.to_json())            
        
        zwrot = json_ok(toReturn)    
    except Exception, e:
        log.exception('expection while vesioning',e)    

    return zwrot